<template>
    <div class="container">
        <el-row justify="center">
            <el-col>
                <div class="title">
                    <h1>用户表</h1>
                </div>
            </el-col>
        </el-row>
        <el-row justify="center">
            <el-col :span="20">
                <div class="top">
                    <div style="display: flex">
                        <el-button style="margin-right: 15px" @click="addUserDialog=true" type="primary" size="large">
                            添加用户
                        </el-button>
                        <el-input clearable class="w-50" v-model="search" size="large"
                                  placeholder="请输入用户姓名模糊检索">
                            <template #append>
                                <el-button @click="searchUserByUserName" :icon="<string>Search"/>
                            </template>
                        </el-input>
                    </div>
                </div>
            </el-col>
        </el-row>
        <el-row justify="center">
            <el-col :span="20">
                <div class="bottom">
                    <div class="aside"/>
                    <div class="main">
                        <!--表数据显示 -->
                        <el-table
                                :data="tableData"
                                style="width: 100%"
                                highlight-current-row

                        >
                            <el-table-column width="100px" label="姓名" prop="username"/>
                            <el-table-column label="生日" prop="birthday"/>
                            <el-table-column width="60px" label="性别" prop="sex">
                                <template #default="scope">
                                    {{ scope.row.sex === 1 ? '男' : '女' }}
                                </template>
                            </el-table-column>
                            <el-table-column label="家乡" prop="address"/>
                            <el-table-column align="right">
                                <template #default="scope">
                                    <el-button size="small" @click="handleEdit(scope.$index,scope.row)"
                                    >Edit
                                    </el-button
                                    >
                                    <el-popconfirm
                                            width="220"
                                            confirm-button-text="我就是要删"
                                            cancel-button-text="还是不了.."
                                            :icon="<string>InfoFilled"
                                            icon-color="#626AEF"
                                            title="你确定要删除这个用户嘛?"
                                            @confirm="handleDelete(scope.$index,scope.row)"
                                    >
                                        <template #reference>
                                            <el-button size="small"
                                                       type="danger">Delete
                                            </el-button>
                                        </template>
                                    </el-popconfirm>
                                </template>
                            </el-table-column>
                        </el-table>
                        <div style="display: flex;justify-content: center">
                            <!--                分页器-->
                            <el-pagination
                                    :current-page="pageNo"
                                    :page-size="pageSize"
                                    layout="prev, pager, next"
                                    :total="total"
                                    @current-change="currentChange"
                            />
                        </div>
                    </div>
                </div>
            </el-col>
        </el-row>
    </div>

  <!--添加用户的弹出-->
    <el-dialog v-model="addUserDialog" title="添加用户">
        <el-form :model="addUserForm"
                 ref="addUserFormRef"
                 :rules="addUserRules"
        >
            <el-form-item label="姓名">
                <el-input v-model="addUserForm.username"/>
            </el-form-item>
            <el-form-item label="生日" prop="birthday">
                <el-date-picker
                        v-model="addUserForm.birthday"
                        type="date"
                        placeholder="选择你的出生日期"
                        clearable
                />
            </el-form-item>
            <el-form-item label="性别">
                <el-radio-group v-model="addUserForm.sex">
                    <el-radio :label="'1'">男</el-radio>
                    <el-radio :label="'0'">女</el-radio>
                </el-radio-group>
            </el-form-item>
            <el-form-item label="家乡" prop="address">
                <el-input v-model="addUserForm.address"/>
            </el-form-item>
        </el-form>
        <template #footer>
      <span class="dialog-footer">
        <el-button @click="addUserDialog = false">取消</el-button>
        <el-button type="primary" @click="addUserDialogSubmit">
          添加
        </el-button>
      </span>
        </template>
    </el-dialog>

  <!--修改用户的弹出-->
    <el-dialog v-model="editUserDialog" title="修改用户">
        <el-form :model="editUserFrom"
                 ref="editUserFormRef"
                 :rules="editUserRules"
        >
            <el-form-item label="姓名" prop="editName">
                <el-input v-model="editUserFrom.username"/>
            </el-form-item>
            <el-form-item label="生日" prop="birthday">
                <el-date-picker
                        v-model="editUserFrom.birthday"
                        type="date"
                        placeholder="选择你的出生日期"
                        clearable
                />
            </el-form-item>
            <el-form-item label="性别">
                <el-radio-group v-model="editUserFrom.sex">
                    <el-radio :label="'1'">男</el-radio>
                    <el-radio :label="'0'">女</el-radio>
                </el-radio-group>
            </el-form-item>
            <el-form-item label="家乡" prop="address">
                <el-input v-model="editUserFrom.address"/>
            </el-form-item>
        </el-form>
        <template #footer>
      <span class="dialog-footer">
        <el-button @click="editUserDialog = false">取消</el-button>
        <el-button type="primary" @click="editUserDialogSubmit">
          修改
        </el-button>
      </span>
        </template>
    </el-dialog>
</template>

<script setup lang="ts">
import {Search, InfoFilled} from '@element-plus/icons-vue'
import {onMounted, reactive, ref} from 'vue'
import {ElMessage, FormInstance, FormRules} from "element-plus";
import axios from 'axios'
/*创建axios实例*/
const request = axios.create({
    baseURL: '/api', //请求的基础路径
    timeout: 5000//超时时间，超时失败
})


/*用户表单ts类型*/
interface User {
    id?: number
    username: string
    birthday: Date
    sex: string
    address: string
}

/*表格总数据*/
let tableData = ref<User[]>([])
/*接收增加用户的表单数据*/
let addUserForm = ref<User>({
    username: '',
    birthday: new Date(''),
    sex: "1",
    address: '',
})

/*接收修改用户的表单数据*/
let editUserFrom = ref<User>({
    username: '',
    birthday: new Date(''),
    sex: "1",
    address: '',
})

let addUserFormRef = ref<FormInstance>()
let editUserFormRef = ref<FormInstance>()
/*增加用户表单的自定义验证规则*/
const addUserRules = reactive<FormRules>({
    birthday: [
        {
            type: 'date',
            required: true,
            message: '请选择出生日期!',
            trigger: 'change',
        },
    ],
    address: [
        {
            required: true,
            message: '请输入家乡',
            trigger: 'change',
        },
    ]
})
/*修改用户表单的自定义验证规则*/
const editUserRules = reactive<FormRules>({
    birthday: [
        {
            type: 'date',
            required: true,
            message: '请选择出生日期!',
            trigger: 'change',
        },
    ],
    address: [
        {
            required: true,
            message: '请输入家乡',
            trigger: 'change',
        },
    ]
})

let addUserDialog = ref<boolean>(false)
let editUserDialog = ref<boolean>(false)
const search = ref<string>('')

//分页器
//页码
let pageNo = ref<number>(1)
//一页展示的数据
let pageSize = ref<number>(6)
//存储用户总个数
let total = ref<number>(0)

// 组件挂载完毕，发一次请求
onMounted(() => {
    getUserInfo()
})

/*添加用户提交的回调*/
const addUserDialogSubmit = async () => {
    //判断用户名是否为空
    if (addUserForm.value.username.trim() == "") {
        ElMessage({
            type: 'warning',
            message: '姓名不能为空!'
        })
        return
    }
    //保证表单的两项都符合条件
    await addUserFormRef.value?.validate()
    //获取到的数据往后端发
    try {
        console.log(addUserForm.value)
        let result: any = await request.post<any, any>(`/addUser`, {user: addUserForm.value})
        if (result.data.code === 200) {
            //关闭弹窗
            addUserDialog.value = false;
            await getUserInfo();
            ElMessage({
                type: 'success',
                message: result.data.message
            })
        }
    } catch (e) {
        ElMessage({
            type: 'error',
            message: e.message
        })
    }
    //关闭弹窗,清空数据
    addUserDialog.value = false;
    // 清空表单数据
    addUserForm.value.username = '';
    addUserFormRef.value?.resetFields()
}


/*修改用户提交的回调*/
const editUserDialogSubmit = async () => {
    //判断用户名是否为空
    if (editUserFrom.value.username.trim() == "") {
        ElMessage({
            type: 'warning',
            message: '姓名不能为空!'
        })
        return
    }
    //保证表单的两项都符合条件
    await editUserFormRef.value?.validate()
    //获取到的数据往后端发
    try {
        console.log("修改提交:", editUserFrom.value)
        let result: any = await request.put<any, any>(`/updateUserInfo`, editUserFrom.value)
        if (result.data.code === 200) {
            //关闭弹窗
            editUserDialog.value = false;
            ElMessage({
                type: 'success',
                message: result.data.message
            })
            editUserFormRef.value?.resetFields()
        }
    } catch (e) {
        ElMessage({
            type: 'error',
            message: e.message
        })
    }

}

/*点击修改的回调*/
const handleEdit = (index: number, row: User) => {
    editUserDialog.value = true
    editUserFrom.value = tableData.value[index]
}


/*点击删除的回调*/
const handleDelete = async (index: number, row: User) => {
    console.log(row.id)
    //获取到的数据往后端发,直接删除
    try {
        let result: any = await request.delete <any, any>(`/delete/${row.id}`)
        if (result.data.code === 200) {
            ElMessage({
                type: 'success',
                message: result.data.message
            })
            await getUserInfo();
        }
    } catch (e) {
        ElMessage({
            type: 'error',
            message: e.message
        })
    }
}


/*搜索框的回调*/
const searchUserByUserName = async () => {
    if (search.value.trim() == "") {
        ElMessage({type: 'error', message: '搜索框不能为空'})
    } else {
        //根据用户名字模糊搜索获取用户数据：默认获取第一页，一页5个数据
        try {
            pageNo.value = 1
            let result: any = await request.get <any, any>(`/userInfo/${pageNo.value}/${pageSize.value}?username=${search.value.trim()}`)
            if (result.data.code === 200) {
                tableData.value = result.data.userInfo;
                total.value = <number>result.data.total;
            }
        } catch (e) {
            ElMessage({
                type: 'error',
                message: e.message
            })
        }
    }
}


//获取已有的用户的数据
const getUserInfo = async () => {
    //获取用户数据：默认获取第一页，一页5个数据
    try {
        let result: any = await request.get <any, any>(`/userInfo/${pageNo.value}/${pageSize.value}?username=${search.value.trim()}`)
        if (result.data.code === 200) {
            tableData.value = result.data.userInfo;
            total.value = <number>result.data.total;
        }
    } catch (e) {
        ElMessage({
            type: 'error',
            message: e.message
        })
    }
}


//分页器页码发生变化时的回调
const currentChange = (e) => {
    pageNo.value = e
    getUserInfo()
}

</script>


<style scoped lang="scss">
.container {
  width: 100%;
  margin: 0;

  .title {
    width: 100%;
    height: 80px;
    display: flex;
    justify-content: center;
  }

  .top {
    width: 100%;
    height: 100%;
  }

  .bottom {
    margin-top: 10px;
    width: 100%;
    height: 100%;
    display: flex;

    .aside {
      width: 20%;
      height: 100%;
      //background-image:url(@/assets/about-bgm.webp);
      background-image: url(@/assets/about-bgm2.webp);
      background-size: contain;
      background-position: center;
      background-repeat: no-repeat;
    }
    .main {
      width: 80%;
      height: 100%;
    }
  }
}
</style>